package com.focusai.efairy.ui.activity.announce;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.focusai.efairy.R;
import com.focusai.efairy.model.project.ProjectItem;
import com.focusai.efairy.model.request.PostAnnounceItemRequest;
import com.focusai.efairy.network.HttpManager;
import com.focusai.efairy.network.Response;
import com.focusai.efairy.network.exception.NetworkException;
import com.focusai.efairy.ui.adapter.announce.InputSelectProjectAdapter;
import com.focusai.efairy.ui.adapter.base.BaseRecyclerAdapter;
import com.focusai.efairy.ui.adapter.base.BaseRecyclerViewHolder;
import com.focusai.efairy.ui.adapter.base.RecycleViewDivider;
import com.focusai.efairy.ui.base.SwipeBackBaseActivity;
import com.focusai.efairy.ui.iview.IUpLoadFileListView;
import com.focusai.efairy.ui.presenter.UpLoadFilePresenter;
import com.focusai.efairy.ui.widget.FullyLinearLayoutManager;
import com.focusai.efairy.ui.widget.InputGirdImageView;
import com.focusai.efairy.utils.ActivityUtils;
import com.focusai.efairy.utils.ImageUtils;
import com.focusai.efairy.utils.ScreenUtil;
import com.focusai.efairy.utils.permission.PermissionListener;
import com.focusai.efairy.utils.permission.PermissionUtil;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import me.iwf.photopicker.PhotoPickerActivity;
import me.iwf.photopicker.utils.PhotoPickerIntent;

/**
 * Created by luo_guangwen on 2017/10/13.
 */

public class InputAnnounceActivity extends SwipeBackBaseActivity implements View.OnClickListener {
    public final static String KEY_DEV_ID = "key_dev_item";

    private final static int REQUEST_CODE_ALBUM = 100; //打开相册回调
    private final static int REQUEST_CODE_PREVIEW = 101; //打开图片预览
    private final static int REQUEST_CODE_SEE_RANGE = 102;
    private final static int EVENT_UPLOAD = 102;
    private final static int EVENT_UPLOAD_FILE_SUCCUSS = 103;
    private final static int EVENT_UPLOAD_FILE_FAIL = 104;
    private InputGirdImageView girdImageView;
    private RecyclerView projectRecyclerView;
    private TextView textWhoSee;
    private EditText editTitle;
    private InputSelectProjectAdapter projectAdapter;
    private ArrayList<String> fileImageList;
    private UpLoadFilePresenter upLoadFilePresenter;
    private ArrayList<ProjectItem> projectItems;
    private int visibilityMode = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_input_announce);
        initView();
        bindEvents();
        setDefaultValues();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuItem menuItem1 = menu.add(MENU_GROUP_ID, MENU_ITEM_ADD, 0, R.string.send).setTitle(R.string.send);
        MenuItemCompat.setShowAsAction(menuItem1, MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == MENU_ITEM_ADD) {
            if (verilyParams()){
                getProcHandler().sendEmptyMessage(EVENT_UPLOAD);
            }
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void initView() {
        girdImageView = findView(R.id.grid_img_view);
        projectRecyclerView = findView(R.id.rcycview_list);
        textWhoSee = findView(R.id.text_who_see);
        editTitle = findView(R.id.edit_announce_title);

    }


    @Override
    protected void bindEvents() {
        findView(R.id.ll_who_can_see).setOnClickListener(this);
        girdImageView.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseRecyclerViewHolder holder) {
                String path = girdImageView.getItem(holder);
                if (InputGirdImageView.LAST.equals(path)) {
                    openPhotoPickerActivity(girdImageView.DEFAUTECOUNT - fileImageList.size());
                } else {
                    ActivityUtils.openPhotoPagerActivity(InputAnnounceActivity.this, REQUEST_CODE_PREVIEW, girdImageView.getPosition(holder), fileImageList, true);
                }
            }
        });
    }

    @Override
    protected boolean useHandleThread() {
        return true;
    }

    @Override
    protected boolean procHandlerCallback(Message msg) {
        switch (msg.what) {
            case EVENT_UPLOAD:
                upLoadFile(fileImageList);
                break;
            default:
                break;
        }
        return super.procHandlerCallback(msg);
    }

    @Override
    protected boolean uiHandlerCallback(Message msg) {
        switch (msg.what) {
            case EVENT_UPLOAD_FILE_SUCCUSS:
                upLoadData((List<String>) msg.obj);
                break;
            case EVENT_UPLOAD_FILE_FAIL:
                closeSingleDialog();
                showToast("上传图片失败");
                break;
            default:
                break;
        }
        return super.uiHandlerCallback(msg);
    }

    @Override
    protected void setDefaultValues() {
        setCenterTitleName("发布公告");
        fileImageList = new ArrayList<>();
        upLoadFilePresenter = new UpLoadFilePresenter();
        projectItems = new ArrayList<>();
        projectAdapter = new InputSelectProjectAdapter(getContext());
        projectRecyclerView.setAdapter(projectAdapter);
        projectRecyclerView.setLayoutManager(new FullyLinearLayoutManager(getContext()));
        projectRecyclerView.addItemDecoration(new RecycleViewDivider(
                mContext, LinearLayoutManager.VERTICAL, ScreenUtil.dp2pix(1), getResources().getColor(R.color.main_line_gray)));
        projectAdapter.refreshData(projectItems);
    }

    private boolean verilyParams(){
        if (TextUtils.isEmpty(editTitle.getText().toString())){
            showToast("请输入公告标题");
            return false;
        }
        if (TextUtils.isEmpty(girdImageView.getContentText())){
            showToast("请输入公告内容");
            return false;
        }
        if (visibilityMode == 2 && projectItems.size() == 0){
            showToast("请选择公告可见的项目");
            return false;
        }
        if (visibilityMode == 3 && projectItems.size() == 0){
            showToast("请选择公告不可见的项目");
            return false;
        }
        return true;
    }
    /**
     * 打开相册
     */
    private void openPhotoPickerActivity(final int count) {
        checkPermission(PermissionUtil.PERMISSION_STORAGE, new PermissionListener() {
            @Override
            public void onSucceed(int requestCode, List<String> grantedList) {
                PhotoPickerIntent intent = new PhotoPickerIntent(getContext());
                intent.setPhotoCount(count);
                intent.setShowCamera(false);
                startActivityForResult(intent, REQUEST_CODE_ALBUM);
            }

            @Override
            public void onFailed(int requestCode, List<String> deniedList) {
                showToast("应用没读SD卡权限");
            }
        }, Manifest.permission.READ_EXTERNAL_STORAGE);

    }


    private void upLoadData(List<String> urlList) {
        PostAnnounceItemRequest.UploadEntry entry = new PostAnnounceItemRequest.UploadEntry();
        entry.visibility_mode = visibilityMode;
        entry.efairyannouncement_info = new PostAnnounceItemRequest.UploadAnnounceInfo();
        entry.efairyannouncement_info.efairyannouncement_title = editTitle.getText().toString();
        entry.efairyannouncement_info.efairyannouncement_content = girdImageView.getContentText();
        entry.efairyannouncement_info.efairyannouncement_image_list = urlList;
        entry.project_id_list = new ArrayList<>();
        for (ProjectItem item:projectItems){
            entry.project_id_list.add(item.efairyproject_id);
        }
        HttpManager.getInstance().sendRequest(new PostAnnounceItemRequest(entry, new Response.Listener<String>() {
            @Override
            protected void onSuccess(String response) {
                closeSingleDialog();
                showToast("公告发布成功");
                setResult(RESULT_OK);
                finish();
            }

            @Override
            protected void onFail(NetworkException exception) {
                closeSingleDialog();
                showToast("公告发布失败");
                doException(exception);
            }
        }));
    }

    private void upLoadFile(List<String> fileOldPath) {
        showProgressDialog("正在上传数据..");
        if (fileOldPath == null || fileOldPath.size() == 0) {
            Message msg = getUiHandler().obtainMessage();
            msg.what = EVENT_UPLOAD_FILE_SUCCUSS;
            msg.obj = new ArrayList<>();
            getUiHandler().sendMessage(msg);
            return;
        }
        List<String> newImagePaths = new ArrayList<>();
        for (String oldPath : fileOldPath) {
            String compressImageFile = ImageUtils.saveCompressImageFile(oldPath);
            if (!TextUtils.isEmpty(compressImageFile)) {
                newImagePaths.add(compressImageFile);
            }
        }
        upLoadFilePresenter.upLaodFiles(newImagePaths, 0, new IUpLoadFileListView() {
            @Override
            public void onUpLoadFileSeccuss(LinkedHashMap<String, String> urlMap) {
                Iterator it = urlMap.entrySet().iterator();
                List<String> urlList = new ArrayList<>();
                while (it.hasNext()) {
                    urlList.add((String) ((Map.Entry) it.next()).getKey());
                }
                Message msg = getUiHandler().obtainMessage();
                msg.what = EVENT_UPLOAD_FILE_SUCCUSS;
                msg.obj = urlList;
                getUiHandler().sendMessage(msg);
            }

            @Override
            public void onUpLoadFileFail(String errormsg) {
                getUiHandler().sendEmptyMessage(EVENT_UPLOAD_FILE_FAIL);
            }

            @Override
            public void onUpLoaditemSussuss(String url, int position, int count) {
                showProgressDialog("正在上传图片" + position + "/" + count);
            }
        });
    }

    private void showProgressDialog(String text) {
        showSingleDialog(text);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_who_can_see:
                Intent intent = new Intent(getContext(),AnnounceSeeRangeActivity.class);
                intent.putExtra(AnnounceSeeRangeActivity.KEY_VISIBILITY_MODE,visibilityMode);
                intent.putExtra(AnnounceSeeRangeActivity.KEY_PROJECT_ITEMS,projectItems);
                startActivityForResult(intent,REQUEST_CODE_SEE_RANGE);
                break;
            default:
                break;
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_ALBUM:
                    ArrayList<String> arrayList = data.getStringArrayListExtra(PhotoPickerActivity.KEY_SELECTED_PHOTOS);
                    if (arrayList != null) {
                        fileImageList.addAll(arrayList);
                        girdImageView.refreshData(fileImageList);
                    }
                    break;
                case REQUEST_CODE_PREVIEW:
                    ArrayList<String> arrayList1 = data.getStringArrayListExtra(PhotoPickerActivity.KEY_SELECTED_PHOTOS);
                    if (arrayList1 != null) {
                        fileImageList.clear();
                        fileImageList.addAll(arrayList1);
                        girdImageView.refreshData(fileImageList);
                    }
                    break;
                case REQUEST_CODE_SEE_RANGE:
                    visibilityMode = data.getIntExtra(AnnounceSeeRangeActivity.KEY_VISIBILITY_MODE,1);
                    if (visibilityMode == 1){
                        textWhoSee.setText(R.string.all_can_see);
                    }else if (visibilityMode == 2){
                        textWhoSee.setText(R.string.part_can_see);
                    }else if (visibilityMode == 3){
                        textWhoSee.setText(R.string.part_cannot_see);
                    }
                    ArrayList list = (ArrayList<ProjectItem>) data.getSerializableExtra(AnnounceSeeRangeActivity.KEY_PROJECT_ITEMS);
                    if (list != null){
                        projectItems.clear();
                        projectItems.addAll(list);
                        projectAdapter.refreshData(projectItems);
                    }
                    break;
                default:
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
